package com.robert.cool.weather.mvp.ui.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.gyf.immersionbar.ImmersionBar;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.http.imageloader.glide.ImageConfigImpl;
import com.jess.arms.utils.ArmsUtils;
import com.robert.cool.weather.R;
import com.robert.cool.weather.app.service.AutoUpdateService;
import com.robert.cool.weather.di.component.DaggerWeatherComponent;
import com.robert.cool.weather.mvp.contract.WeatherContract;
import com.robert.cool.weather.mvp.model.entity.C;
import com.robert.cool.weather.mvp.model.entity.Weather;
import com.robert.cool.weather.mvp.presenter.WeatherPresenter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/23/2020 13:02
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class WeatherActivity extends BaseActivity<WeatherPresenter> implements WeatherContract.View {

    @BindView(R.id.title_city)
    TextView titleCity;
    @BindView(R.id.title_update_time)
    TextView titleUpdateTime;
    @BindView(R.id.degree_text)
    TextView degreeText;
    @BindView(R.id.weather_info_text)
    TextView weatherInfoText;
    @BindView(R.id.forecast_layout)
    LinearLayout forecastLayout;
    @BindView(R.id.comfort_text)
    TextView comfortText;
    @BindView(R.id.car_wash_text)
    TextView carWashText;
    @BindView(R.id.sport_text)
    TextView sportText;
    @BindView(R.id.weather_layout)
    ScrollView weatherLayout;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.bing_pic_img)
    ImageView bingPicImg;
    @BindView(R.id.nav_button)
    Button navButton;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    private String mWeatherId;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerWeatherComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_weather; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        ImmersionBar.with(this)
                .init();
        initRefreshLayout();
        mWeatherId = getIntent().getStringExtra(C.WeatherId);
        mPresenter.requestWeather(mWeatherId, false);
    }

    private void initRefreshLayout() {
        smartRefreshLayout.autoRefresh();
        smartRefreshLayout.setEnableLoadMore(false);
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.requestWeather(mWeatherId, true);
            }
        });
    }

    @Override
    public void showLoading() {
        weatherLayout.setVisibility(View.INVISIBLE);
    }

    @Override
    public void hideLoading() {
        weatherLayout.setVisibility(View.VISIBLE);
        smartRefreshLayout.finishRefresh();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void showWeather(Weather weather) {
        Weather.HeWeather6Bean bean = weather.getHeWeather6().get(0);
        String cityName = bean.getBasic().getLocation();
        String updateTime = bean.getUpdate().getLoc().split(" ")[1];
        String degree = bean.getNow().getTmp() + "℃";
        String weatherInfo = bean.getNow().getCond_txt();
        titleCity.setText(cityName);
        titleUpdateTime.setText(updateTime);
        degreeText.setText(degree);
        weatherInfoText.setText(weatherInfo);
        forecastLayout.removeAllViews();
        //预报
        List<Weather.HeWeather6Bean.DailyForecastBean> forecastList = bean.getDaily_forecast();
        for (Weather.HeWeather6Bean.DailyForecastBean forecastBean : forecastList) {
            View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false);
            TextView dateText = view.findViewById(R.id.date_text);
            TextView infoText = view.findViewById(R.id.info_text);
            TextView maxText = view.findViewById(R.id.max_text);
            TextView minText = view.findViewById(R.id.min_text);
            dateText.setText(forecastBean.getDate());
            infoText.setText(forecastBean.getCond_txt_d());
            maxText.setText(forecastBean.getTmp_max());
            minText.setText(forecastBean.getTmp_min());
            forecastLayout.addView(view);
        }
        String comfort = null, drsg = null, flu = null, sport = null, trav = null, uv = null, cw = null, air = null;
        List<Weather.HeWeather6Bean.LifestyleBean> lifestyles = bean.getLifestyle();
        for (Weather.HeWeather6Bean.LifestyleBean lifestyle : lifestyles) {
            String content = lifestyle.getBrf() + "\n" + lifestyle.getTxt();
            switch (lifestyle.getType()) {
                case "comf":
                    comfort = "舒适度：" + content;
                    break;
                case "drsg":
                    drsg = "穿衣：" + content;
                    break;
                case "flu":
                    flu = "流感：" + content;
                    break;
                case "sport":
                    sport = "运动：" + content;
                    break;
                case "trav":
                    trav = "旅游：" + content;
                    break;
                case "uv":
                    uv = "紫外线：" + content;
                    break;
                case "cw":
                    cw = "洗车：" + content;
                    break;
                case "air":
                    air = "空气质量：" + content;
                    break;
            }
        }
        comfortText.setText(comfort);
        carWashText.setText(cw);
        sportText.setText(sport);
        Intent intent = new Intent(getApplicationContext(), AutoUpdateService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            startForegroundService(intent);
        }else {
            startService(intent);
        }
    }

    @Override
    public void showPic(String data) {
        ImageLoader imageLoader = ArmsUtils.obtainAppComponentFromContext(this).imageLoader();
        imageLoader.loadImage(this, ImageConfigImpl.builder().url(data).imageView(bingPicImg).build());
    }

    @OnClick(R.id.nav_button)
    public void onViewClicked() {
        drawerLayout.openDrawer(GravityCompat.START);
    }

    public void changeCity(String weatherId) {
        drawerLayout.closeDrawers();
        mWeatherId = weatherId;
        smartRefreshLayout.autoRefresh();
    }
}
